#include <iostream>
#include <vector>

using std::cout;
using std::endl;
using std::vector;

template <typename Container>
void display(const Container &con)
{
    for(auto &elem : con)
    {
        cout << elem << "  ";
    }
    cout << endl;
}

void printCapacity(const vector<int> &con)
{
    cout << "size() = " << con.size() << endl;
    cout << "capacity() = " << con.capacity() << endl;
}

void test()
{
    vector<int> number = {1, 4, 6, 8, 9, 10, 5, 7};
    display(number);
    printCapacity(number);

    cout << endl << "在vector的尾部进行插入与删除" << endl;
    number.push_back(22);
    number.push_back(33);
    display(number);
    printCapacity(number);

    cout << endl << "在vector的任意位置进行插入" << endl;
    auto it = number.begin();
    it += 2;
    cout << "*it = " << *it <<endl;
    number.insert(it, 111);
    display(number);
    printCapacity(number);
    cout << "*it = " << *it <<endl;

    cout << endl << endl;
    //总结：vector的push_back之所以可以进行2倍扩容，是因为每次插入元素的
    //个数是1个（固定的），所以按照2倍扩容没有什么问题;但是对于insert
    //插入元素的时候，不知道每次插入元素的个数是多少，所以不能按照某个
    //固定值的两倍，才有了下面的分配方式
    //size() = m = 11, capacity() = n = 16, 插入元素的个数t
    //1、t < n - m,不会发生扩容
    //2、n - m < t < m,会按照2 * size()进行扩容
    //3、n - m < t, m < t < n,会按照m + t进行扩容
    //4、n - m < t, t > n,会按照m + t进行扩容
    it = number.begin();
    it += 2;
    cout << "*it = " << *it <<endl;
    number.insert(it, 100, 200);
    display(number);
    printCapacity(number);
    cout << "*it = " << *it <<endl;

    cout << endl << endl;
    vector<int> vec = {333, 555, 444};
    it = number.begin();
    it += 2;
    cout << "*it = " << *it <<endl;
    number.insert(it, vec.begin(), vec.end());
    display(number);
    printCapacity(number);
    cout << "*it = " << *it <<endl;
}

int main(int argc, char *argv[])
{
    test();
    return 0;
}

